import java.util.Random;

public class ConnectionImpl implements Connection{
    private int connectionNumber;
    private boolean using = false;

    public ConnectionImpl(int connectionNumber){
        this.connectionNumber = connectionNumber;

        //模拟网络延迟
        delay(500,1000);
    }

    private void delay(int start,int end){
        int delay = new Random().nextInt(end-start)+end;
        try{
            Thread.sleep(delay);
        }catch(Exception ex){
            throw new RuntimeException(ex);
        }
    }

    @Override
    public synchronized boolean isIdle(){
        return !using;
    }

    @Override
    public synchronized void startWork(){
        using = true;
    }

    @Override
    public synchronized void endWork(){
        using = false;
    }

    @Override
    public void sendData(String data){
        delay(1000,2000);
        System.out.println(String.format("Connection #%04d: %s", connectionNumber, data));
    }
}
